package com.zsl.controller;

import com.zsl.service.UsersService;
import com.zsl.service.impl.UsersServiceImpl;
import com.zsl.util.Base64Encoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class UserLogin extends HttpServlet {
    private final UsersService usersService = new UsersServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //获取用户的登录信息
        String name = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        //密码使用MD5加密
        pwd = Base64Encoder.encode(pwd);
        //验证是否正确
        String str;
        if (!usersService.isReallyUsers(name, pwd)) {
            str = "{\"msg\":\"登陆失败\",\"success\":\"0\"}";
        } else {
            str = "{\"msg\":\"登陆成功\",\"success\":\"1\"}";
            //获取Session
            HttpSession session = request.getSession();
            //设置Session
            session.setAttribute("user", name);
            //设置时间
            SimpleDateFormat df = new SimpleDateFormat("yyyy:MM:dd:HH:mm:ss");//设置日期格式
            session.setAttribute("loginTime", df.format(new Date()));
            //将ServletContext+1
            ServletContext servletContext = request.getServletContext();
            Integer count = (Integer)servletContext.getAttribute("count");
            if (count == null){
                servletContext.setAttribute("count",1);
            }else {
                servletContext.setAttribute("count",++count);
            }
        }
        //返回对应的信息
        out.write(str);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
